package com.mlnx.work.dao.typehandler;

import com.alibaba.fastjson.JSONObject;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;

@MappedTypes(Date.class) //映射的Java数据类型
@MappedJdbcTypes(JdbcType.BIGINT)  //映射的JDBC数据类型
public class LongTypeHandler extends BaseTypeHandler<Date> {
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Date param,
                                    JdbcType jdbcType) throws SQLException {
        ps.setString(i, JSONObject.toJSONString(param));
    }

    @Override
    public Date getNullableResult(ResultSet rs, String columnName)
            throws SQLException {
        Long tempLong = rs.getLong(columnName);
        if (null != tempLong) {
            if (tempLong == 0)
                return null;
            return new Date(tempLong);
        }
        return null;
    }


    @Override
    public Date getNullableResult(ResultSet rs, int columnIndex)
            throws SQLException {
        Long tempLong = rs.getLong(columnIndex);
        if (null != tempLong) {
            if (tempLong == 0)
                return null;
            return new Date(tempLong);
        }
        return null;
    }


    @Override
    public Date getNullableResult(CallableStatement cs, int columnIndex)
            throws SQLException {
        Long tempLong = cs.getLong(columnIndex);
        if (null != tempLong) {
            if (tempLong == 0)
                return null;
            return new Date(tempLong);
        }
        return null;
    }

}